<template>
	<view>
		<cu-page-bg></cu-page-bg>
		<view class="cu-w-100">
			<cu-navbar v-if="showLeftClick" title="记一笔" :placeholder="true" @leftClick="vk.navigateBack()" :showLeft="true" :leftIconColor="{color:backgroundStyle.color}" :titleStyle="{color:backgroundStyle.color}" :style="getBackgroundStyle"
				bgColor="rgb(255,255,255,0)"></cu-navbar>
			<cu-navbar v-if="!showLeftClick" title="记一笔" :placeholder="true" :leftIconColor="{color:backgroundStyle.color}" :titleStyle="{color:backgroundStyle.color}" :style="getBackgroundStyle"
					bgColor="rgb(255,255,255,0)"></cu-navbar>
			<view class="cu-w-100 cu-p-20 cu-border-box">
				<cu-card>
					<view class="cu-w-100 cu-row cu-font-weight cu-text-light-muted cu-font-big cu-py-20">
						<view style="border-left: 10rpx solid #CCC; margin-right: 20rpx;"></view>记账
					</view>
					<u--form labelPosition="left" labelWidth="auto" :labelStyle="{paddingRight:'20rpx'}"
						:model="keepingData" ref="uForm">
						<u-form-item label="收支类型" prop="isExpenses" borderBottom>
							<u-radio-group v-model="keepingData.isExpenses">
								<u-radio label="支出 " name="true"></u-radio>
								<view class="cu-px-40"></view>
								<u-radio label="收入 " name="false"></u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="类型" prop="icon" @click="pickerShow = true" borderBottom>
							<cu-picker :isIcon="true"  :iconStyle="{marginLeft:'40%'}" iconSize="36" customPrefix="iconfont" @confirm="pickerConfirm()" @close="pickerShow = false" 
							@cancel="pickerShow = false" :show="pickerShow" v-model="typeData.icon"
							:columns="userTypeDataPickerData" keyName="icon" iconTextKey="name" :defaultIndex="getDefaultIndex"></cu-picker>
							<view class="cu-w-100 cu-row cu-j-start cu-a-center cu-px-50">
								<cu-icon custom-prefix="iconfont" slot="icon" size="36" :name="selectIcon.icon"></cu-icon>
								<view class="cu-px-20">{{selectIcon.name}}</view>
							</view>
						</u-form-item>
						<u-form-item label="记账日期" @click="datetimePickerShow = true" prop="date" borderBottom>
							<u-datetime-picker :show="datetimePickerShow" @close="datetimePickerShow = false" @cancel="datetimePickerShow = false"
							    @confirm="datetimePickerConfirmFun()" v-model="keepingData.date" mode="date"></u-datetime-picker>
							<view class="cu-w-100 cu-row cu-j-start">{{keepingData.date | formatDate}}</view>
						</u-form-item>
						<u-form-item label="金额" prop="amount" borderBottom>
							<u--input placeholder="请输入金额" v-model="keepingData.amount" border="none"></u--input>
						</u-form-item>
						<u-form-item label="备注" prop="remarks" borderBottom>
							<u--input placeholder="备注" v-model="keepingData.remarks" border="none"></u--input>
						</u-form-item>
						<u-form-item label="账本" prop="booksName" borderBottom>
							<cu-scroll>
								<u-checkbox-group
									v-model="keepingData.booksName"
									placement="row"
									@change="checkboxChange"
									:disabled="!isInsert"
								>
									<u-checkbox
										:customStyle="{marginLeft: '10px'}"
										v-for="(item, index) in allAccountBooks"
										:key="index"
										:label="item.accountBookName"
										:name="item.accountBookName"
									>
									</u-checkbox>
								</u-checkbox-group>
							</cu-scroll>
						</u-form-item>
					</u--form>
					<view class="cu-mt-50">
						<u-button :color="buttonColor" @click="submit">确认</u-button>
					</view>
				</cu-card>
			</view>
		</view>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		props: {
			backgroundStyle: {
				type: Object,
				default: {
					color: "#FFF"
				}
			},
			showLeftClick: {
				type: Boolean,
				default: false
			},
			userInfo: {
				type: Object,
				default:{
					"avatar":"",
					"nickname": ""
				}
			},
			selectKeepData: {
				type: Object,
				default: undefined
			},
		},
		watch: {
			// 监听默认索引的变化，重新设置对应的值
			selectKeepData: {
				immediate: true,
				handler(n) {
					if(vk.myfn.isNotEmpty(this.selectKeepData)) {
						this.isInsert = false
						this.keepingData = vk.pubfn.deepClone(this.selectKeepData);
						this.selectIcon = this.selectKeepData.icon
						let rtn = this.keepingData.amount / 100;
						this.keepingData.amount = rtn.toFixed(2);
						if(vk.myfn.isNotEmpty(this.selectKeepData.checkBookName)) {
							this.checkboxChange(this.selectKeepData.checkBookName)
							delete this.keepingData.checkBookName
						}
						delete this.keepingData.userInf
						delete this.keepingData.iconName
					}
					return n
				}
			},
		},
		computed: {
			getBackgroundStyle() {
				if (vk.myfn.isEmpty(this.userInfo)) {
					this.vk.myfn.gotoPage('/pages/oauth/login/index', 'navigate')
				}
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			},
			getDefaultIndex(){
				if (vk.myfn.isEmpty(this.typeDataColumns)) {
					return -1
				}
				return [this.typeDataColumns[0].indexOf(this.selectIcon)]
			}
		},
		filters: {
			formatDateTime(value) {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				});
			},
			formatDate(value) {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric'
				});
			}
		},
		data() {
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				buttonColor: "linear-gradient(to right, " + vk.getVuex('$app.color.main') + "," + vk.getVuex('$app.color.secondary')+ ")",
				allAccountBooks: vk.getVuex('$accountbook.allAccountBooks'),
				userTypeDataPickerData: vk.getVuex('$typeData.userTypeDataPickerData'),
				keepingData:{
					isExpenses: "true",
					icon:undefined,
					date: Date.now(),
					amount: undefined,
					remarks: undefined,
					books: [],
					booksName: []
				},
				pickerShow:false,
				selectIcon: undefined,
				datetimePickerShow: false,
				isInsert: true,
			};
		},
		onLoad(options) {
			vk = uni.vk;
			this.init(options);
		},
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
			},
			pickerConfirm(e){
				this.pickerShow = false
				this.selectIcon = e.value[0] || undefined;
				this.keepingData.icon = this.selectIcon
			},
			datetimePickerConfirmFun(e){
				if(e.value > Date.now()) {
					vk.alert("记账日期不能大于当前日期", "错误提示");
					return false;
				}
				this.datetimePickerShow = false
			},
			async enqrAllAccountBook() {
				let that = this
				const pagination = {
					"pageIndex": 1,
					"pageSize": 1000
				}
				await vk.callFunction({
					url: 'client/accountbook/kh/enqrAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination
					},
					success: async (res) => {
						await that.$store.dispatch('$accountbook/enqrAccountBook', {
							res
						});
						that.allAccountBooks= vk.getVuex('$accountbook.allAccountBooks');
					},
					fail: (err) => {
						const msg = "查询账本失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			async submit(){
				if (vk.myfn.isEmpty(this.keepingData.icon)) {
					vk.toast("请选择类型", "error");
					return
				}
				else if (vk.myfn.isEmpty(this.keepingData.amount)) {
					vk.toast("请输入金额", "error");
					return
				}
				else if(!vk.myfn.validateAmount(this.keepingData.amount)){
					vk.toast("输入金额有误", "error");
					return
				}
				else if (vk.myfn.isEmpty(this.keepingData.date)) {
					vk.toast("请选择日期", "error");
					return
				}
				else if (this.keepingData.date > Date.now()) {
					vk.alert("不能大于当前日期", "error");
					return
				}
				else if (vk.myfn.isEmpty(this.keepingData.books)) {
					vk.toast("请选择账本", "error");
					return
				}
				
				if(this.keepingData.isExpenses === "true" && Number(this.keepingData.amount) > 0){
					this.keepingData.amount = -this.keepingData.amount
				}
				else if(this.keepingData.isExpenses === "false" && Number(this.keepingData.amount) < 0) {
					this.keepingData.amount = -this.keepingData.amount
				}
				
				if (this.isInsert === true) {
					await this.addKeepingDataFun()
				}
				else {
					console.log(this.keepingData,this.selectKeepData)
					this.updateKeepingDataFun()
				}
				
			},
			checkboxChange(n) {
				if(vk.myfn.isNotEmpty(n)){
					let books = []
					let booksName = []
					for (const str of n) {
					   for (const item of this.allAccountBooks) {
						   if(item.accountBookName === str){
							  books.push(item)
							  booksName.push(str)
						   }
					   }
					}
					this.keepingData.books = books
					this.keepingData.booksName = booksName
				}
				else {
					this.keepingData.books = []
					this.keepingData.booksName = []
				}
			},
			async addKeepingDataFun(){
				let that = this
				await vk.callFunction({
					url: 'client/accounting/record/kh/addKeepingData',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						keepingData: this.keepingData
					},
					success: async (res) => {
						vk.toast("添加成功", "success");
						that.keepingData = {
							isExpenses: "true",
							icon:undefined,
							date: Date.now(),
							amount: undefined,
							remarks: undefined,
							books: [],
							booksName: []
						}
						that.selectIcon= {}
						that.enqrAllAccountBook()
					},
					fail: (err) => {
						const msg = "查询失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			async updateKeepingDataFun(){
				let that = this
				await vk.callFunction({
					url: 'client/accounting/record/kh/updateKeepingData',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						keepingData: this.keepingData,
						oldData: this.selectKeepData
					},
					success: async (res) => {
						vk.toast("修改成功", "success");
						// 重置账本数据，进行查询
						this.navigateBackAndRefresh();
					},
					fail: (err) => {
						const msg = "修改失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			// 当前页的返回逻辑
			navigateBackAndRefresh() {
			  const pages = getCurrentPages(); // 获取页面栈
			  if (pages.length > 1) {
			    const prevPage = pages[pages.length - 2]; // 上一页实例
			    if (prevPage.$vm && prevPage.$vm.onRefresh) {
			      prevPage.$vm.onRefresh(); // 调用上一页的刷新方法（需自定义）
			    }
			    uni.navigateBack({ delta: 1 }); // 返回上一页
			  } else {
			    uni.navigateBack();
			  }
			}
		}
	};
</script>

<style lang="scss" scoped>

</style>